<?php
/**
 * Created by PhpStorm.
 * User: RenBin
 * Date: 2016/1/18
 * Time: 11:00
 */

namespace common\models\Service;


use common\models\DAO\Collect;
use common\models\DAO\UserCharge;
use common\msg\UserMsg;

class CollectService {

    public static function init($userID){
        $collect_info = Collect::find()->where(['userID'=>$userID])->asArray()->groupBy('card')->select('card, count(id) as c')->all();
        $count = 0;
        foreach($collect_info as $v){
            $count += $v['c'];
        }
        return ['info'=>$collect_info, 'count'=>$count];
    }

    public static function deal($userID){
        $date = date('Ymd');
        $is_get = Collect::findOne(['userID'=>$userID, 'date'=>$date]);
        $result['status'] = 0;
        $result['msg'] = UserMsg::$time_out;
		$result['msg'] = UserMsg::$action_end;
            return $result;
        if($is_get){
            $result['msg'] = UserMsg::$action_already;
            return $result;
        }
        $collect_info = Collect::find()->where(['userID'=>$userID])->asArray()->groupBy('card')->select('card, count(id) as c')->all();
        $count = 0;
        $card_arr = [];
        foreach($collect_info as $v){
            $count += $v['c'];
            $card_arr[] = $v['card'];
        }
        $card = mt_rand(1, 12);
        if($collect_info && !in_array($card, $card_arr)){
            if(intval(\Yii::$app->db->createCommand("SELECT COUNT(*) FROM (SELECT s.*, COUNT(s.id) AS c FROM (SELECT * FROM p2p_collect GROUP BY card) s GROUP BY s.userID ) t WHERE c >7")->query()->readAll()) >= 100
                || count($collect_info) == 11 ||
                (count($collect_info) == 7 && intval(UserCharge::find()->where(['userID'=>$userID, 'status'=>1])->sum('money')) < 500000)){
                $key = mt_rand(0, count($collect_info) - 1);
                $card = $card_arr[$key];
            }
        }
        $collectMolde = new Collect();
        $collectMolde->userID = $userID;
        $collectMolde->createTime = time();
        $collectMolde->card = $card;
        $collectMolde->date = $date;
        $collect_result = $collectMolde->save();
        if(!$collect_result)
            return $result;
        return ['status'=>1 , 'card'=>$card - 1];

    }
}